<template>
  <div class="home">
    <baidu-map @ready="handler" class="map" :center="{lng: 105.939068,lat: 29.373368}" :zoom="18"
               :scroll-wheel-zoom="true"
               @click="getPoint"
    >
      <bm-marker :position="{lng: model.lng, lat: model.lat}"/>
    </baidu-map>

    <!-- 添加或修改河流事件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">


        <el-form-item label="河流名称" prop="riverId">
          <el-select v-model="form.riverId" placeholder="请选择河流名称" @change="riverChange" >
            <el-option
              v-for="dict in riverList"
              :key="dict.riverId"
              :label="dict.riverName"
              :value="parseInt(dict.riverId)"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="dict in dict.type.river_event_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="事件级别" prop="level">
          <el-radio-group v-model="form.level">
            <el-radio
              v-for="dict in dict.type.river_patrol_level"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="事件标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入事件标题" />
        </el-form-item>
        <el-form-item label="事件内容描述" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="事件日期" prop="eventTime">
          <el-date-picker
            v-model="form.eventTime"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>


        <el-form-item label="图片" prop="img">
          <image-upload v-model="form.img"/>
        </el-form-item>

        <el-form-item label="处理状态" prop="resultStatus">
          <el-radio-group v-model="form.resultStatus">
            <el-radio
              v-for="dict in dict.type.river_patrol_solve"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理结果" prop="resultContent">
          <el-input v-model="form.resultContent" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="处理结果图例" prop="resultImg">
          <image-upload v-model="form.resultImg"/>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEvent, getEvent, addEvent, updateEvent } from '@/api/riv/event'
import { listInfo } from '@/api/riv/info'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'Index',
  dicts: ['river_patrol_level', 'river_event_type', 'river_patrol_solve'],
  data() {
    return {
      point:{lng: null, lat: null},

      riverList:[],
      riverTotal:0,

      riverName:"",
      leaderId:"",
      leaderName:"",
      // 查询参数
      form: {},
      BMap: null,
      map: null,
      // 河道管理表格数据
      infoList: [],
      // 河流事件表格数据
      eventList: [],
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      model: {
        lng: '',
        lat: '',
        address: ''
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: '上报人不能为空', trigger: 'change' }
        ],
        riverId: [
          { required: true, message: '河流不能为空', trigger: 'change' }
        ],
        placeLng: [
          { required: true, message: '地点坐标不能为空', trigger: 'blur' }
        ],
        placeLat: [
          { required: true, message: '地点坐标不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '类型不能为空', trigger: 'change' }
        ],
        degree: [
          { required: true, message: '程度不能为空', trigger: 'change' }
        ],
        content: [
          { required: true, message: '事件内容不能为空', trigger: 'blur' }
        ],
        eventTime: [
          { required: true, message: "日期不能为空", trigger: "change" }
        ],
        level: [
          { required: true, message: "事件级别不能为空", trigger: "change" }
        ],
        title: [
          { required: true, message: "标题不能为空", trigger: "change" }
        ],
        resultStatus: [
          { required: true, message: "处理状态不能为空", trigger: "change" }
        ],
      },


    }
  },
  created() {
    this.getEventList();
    this.getRiver();
    this.getList();
  },


  methods: {

    getPoint(e){
      this.point.lng = e.point.lng
      this.point.lat = e.point.lat
    },
    //查询河流name
    riverChange(r){
      this.riverList.forEach(item => {
        if(item.riverId == r){
          this.riverName = item.riverName
          this.leaderId = item.leaderId
          this.leaderName = item.leaderName
        }
      })
    },

    /** 查询河流事件列表 */
    getList() {
      this.loading = true;
      listEvent(this.queryParams).then(response => {
        this.eventList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 查询河流名称 */
    getRiver() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.riverList = response.rows;
        this.riverTotal = response.total;
        this.loading = false;

        console.log(this.riverList)
      });
    },


    goTarget(href) {
      window.open(href, '_blank')
    },
    /**查询河流事件列表*/
    getEventList(){
      let that=this
      this.loading=true
      const eventTypeMap={
        1:'污染',
        2:'汛情',
        3:'低水位',
      };
      const alarmTypeMap={
        0:'标准事件',
        1:'严重事件',
      };

      listEvent(this.queryParams).then(response=>{
        this.eventList=response.rows;
        this.eventList.forEach(item=>{

          console.log(item.type);
          const typeTxt=eventTypeMap[item.type]||'河面侵占';
          const alarmType=alarmTypeMap[item.level]||'紧急事件';
          const content=`
<table>
<tr><td><strongstyle="display:block;text-align:center;border-bottom:1pxsolid#00afff;padding-bottom:5px">${alarmType}</strong></td></tr>
<tr><td>事件编号：${item.eventId}</td></tr>
<tr><td>事件标题：${item.title}</td></tr>
<tr><td>河流名称：${item.riverName}</td></tr>
<tr><td>河长：${item.leaderName}</td></tr>
<tr><td>上报人：${item.userName}</td></tr>
<tr><td>事件类型：${typeTxt}</td></tr>
<tr><td>事件时间：${parseTime(item.eventTime,'{y}-{m}-{d}')}</td></tr>
</table>
`;

          let coordinate = JSON.parse(item.coordinate);

          const marker=new this.BMap.Marker(
            new this.BMap.Point(coordinate.lng,coordinate.lat),
            {
              title:item.degree,
              dragging:true
            }
          );

          this.map.addOverlay(marker);
          marker.addEventListener('mouseover',e=>{
            const p=e.target;
            const point=new this.BMap.Point(p.getPosition().lng,p.getPosition().lat);
            const infoWindow=new this.BMap.InfoWindow(content);
            this.map.openInfoWindow(infoWindow,point);
          });
        });
        this.loading=false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        eventId: null,
        userId: null,
        riverId: null,
        placeLng: null,
        placeLat: null,
        type: null,
        degree: null,
        content: null,
        imgs: null,
        videos: null,
        state: null,
        dealId: null,
        dealTime: null,
        dealContent: null
      }
      this.resetForm('form')
    },
    // 初始化地图
    handler({ BMap, map }) {
      this.map = map
      this.BMap = BMap
      const viewthis = this

      map.addEventListener('click', function(e) {
        viewthis.model.lng = e.point.lng
        viewthis.model.lat = e.point.lat
        viewthis.reset()
        viewthis.open = true
        viewthis.title = '添加河流事件'
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const eventId = row.eventId || this.ids
      getEvent(eventId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改河流事件'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {

          this.form.riverName=this.riverName
          this.form.leaderId=this.leaderId
          this.form.leaderName=this.leaderName


          if(this.form.userId == null || this.form.userId === ""){
            this.form.userId = this.$store.state.user.id;
            this.form.userName = this.$store.state.user.name;
          }else{
            this.form.updateId = this.$store.state.user.id;
            this.form.updateUser = this.$store.state.user.name;
          }

          this.form.coordinate = JSON.stringify(this.point);

          if (this.form.eventId != null) {
            updateEvent(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getEventList()
            })
          } else {
            addEvent(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getEventList()
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">

.map {
  width: 100%;
  height: calc(100vh - 84px);
}

</style>

